package xt.outfood.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xt.outfood.common.Result;
import xt.outfood.entity.User;


import xt.outfood.mail.SendMailService;
import xt.outfood.mail.SendMailServiceImpl;
import xt.outfood.service.UserService;
import xt.outfood.utils.ValidateCodeUtils;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户控制类")
public class UserController {
    @Autowired
    private SendMailService sendMailService;
    @Autowired
    private UserService userService;
    //进行redis缓存
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码,Session中的短信验证码默认是30分钟
     *
     * @param user
     * @param session
     * @return
     */
    @ApiOperation(value = "发送用户消息")
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session) throws MessagingException {
        log.info("user:{}", user);
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
//            String code = "123456";
            log.info("code={}", code);
            //发送邮件
            sendMailService.sendMail(phone, code);
//            session.setAttribute(phone,code);
            //将生成的验证码缓存到redis中，并设置有效期为5min
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.success("验证码已发送，注意查收");
        }
        return Result.error("验证码发送失败，注意检查");
    }


    @PostMapping("/login")
    public Result<User> login(@RequestBody Map map, HttpSession session) {
        log.info("user:{}", map.toString());
        //获取传来的邮箱号
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //获取session中的phone和code
//        Object sessionPhone = session.getAttribute(phone);
        Object redisSession = redisTemplate.opsForValue().get(phone);
        if (redisSession != null && redisSession.equals(code)) {
            //判断是否一样，一样则登录成功

            //判断当前用户是否是新用户，如果是则自动完成注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //登录成功，把id存入session中
            session.setAttribute("user", user.getId());
            //如果登录成功则删除redis缓存
            redisTemplate.delete(phone);
            return Result.success(user);


        }

        return Result.error("登录失败,请重新登录");
    }

    @PostMapping("/loginout")
    public Result<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("userPhone");
        return Result.success("安全退出成功！");
    }
}
